package com.g4.shoppingsingle.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.g4.shoppingsingle.common.Result;
import com.g4.shoppingsingle.pojo.DdCartDetail;
import com.g4.shoppingsingle.pojo.DdOrderInfo;
import com.g4.shoppingsingle.pojo.DdUsersInfo;
import com.g4.shoppingsingle.service.IDdCartDetailService;
import com.g4.shoppingsingle.service.IDdOrderInfoService;
import com.g4.shoppingsingle.service.IDdUsersInfoService;
import com.g4.shoppingsingle.vo.AddOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-10-27
 */
@Slf4j
@RestController
@RequestMapping("/shoppingsingle/ddOrderInfo")
public class DdOrderInfoController {

    @Autowired
    private IDdOrderInfoService ddOrderInfoService;

    @Autowired
    private IDdUsersInfoService ddUsersInfoService;

    @Autowired
    private IDdCartDetailService ddCartDetailService;

    /**
     * 获取当前登录用户的订单
     * @return
     */
    @GetMapping("/dingdanzhongxin")
    @PreAuthorize("isAuthenticated()")
    public List<DdOrderInfo> orders(){
        //获取当前登录用户的订单
        DdUsersInfo ddUsersInfo = ddUsersInfoService.getMe();
        //
        List<DdOrderInfo> orders=ddOrderInfoService.getOrders(ddUsersInfo.getId());
        log.info("我的订单:"+orders);
        return orders;
    }

    /**
     * 从购物车选购下单
     * @param
     * @return
     */
    @PostMapping("/addOrder")
    @PreAuthorize("isAuthenticated()")
    public Result cartAddOrder(@RequestBody List<AddOrderVo> list){
        log.info("添加订单参数为--：" + list.toString());

        //更新购物车
        for (AddOrderVo vo : list){
            DdCartDetail pojo = new DdCartDetail();
            pojo.setNum(vo.getNum());
            pojo.setId(vo.getCartId());
            //更新购买的数量
            ddCartDetailService.updateById(pojo);
        }

        //添加订单
        String orderId = ddOrderInfoService.cartAddOrder(list);

        return Result.ok(orderId);
    }

    /**
     * 立即选购下单
     * @param typeId
     * @param productId
     * @return
     */
    @PostMapping("/addOrder/{typeId}/{productId}")
    public Result addOrder(@PathVariable Integer typeId,
                             @PathVariable Integer productId){
        log.info("添加订单参数如下--: ");
        log.info("配置id--: " + typeId);
        log.info("商品id--: " + productId);

        String orderId = ddOrderInfoService.addOrder(typeId, productId);
        return Result.ok(orderId);
    }




}
